package cn.xuchunh.campusbbs.ui.fragments;

import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.PagerAdapter;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import cn.xuchunh.campusbbs.R;
import cn.xuchunh.campusbbs.adapter.HomePageAdapter;
import cn.xuchunh.campusbbs.base.BaseFragment;
import cn.xuchunh.campusbbs.base.BaseRefreshListFragment;
import cn.xuchunh.campusbbs.bean.User;
import cn.xuchunh.campusbbs.utils.IntentParamsKey;

/**
 * Created by XuChunH on 2015/10/19.
 */
public class UserFragment extends TabFragment {

    private BaseRefreshListFragment userTopicListFragment, userAlbumListFragment;
    private User user;

    public static UserFragment newInstance(User user) {

        Bundle args = new Bundle();
        args.putSerializable(IntentParamsKey.USER, user);
        UserFragment fragment = new UserFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected PagerAdapter createAdapter() {
        List<BaseFragment> fragmentList = new ArrayList<>();
        fragmentList.add(UserProfileFragment.newInstance(user));
        userTopicListFragment = UserTopicListFragment.newInstance(user);
        userAlbumListFragment = UserAlbumListFragment.newInstance(user);
        fragmentList.add(userTopicListFragment);
        fragmentList.add(userAlbumListFragment);
        List<String> titleList = Arrays.asList(getResources().getStringArray(R.array.user_info_titles));
        return new HomePageAdapter(getChildFragmentManager(), fragmentList, titleList);
    }

    @Override
    protected void afterInitView() {
        super.afterInitView();
        getTabLayout().setTabMode(TabLayout.MODE_SCROLLABLE);
        getViewPager().setOffscreenPageLimit(3);
    }

    public void updateRefreshState(boolean enable) {
        if (userAlbumListFragment != null && userTopicListFragment != null) {
            userAlbumListFragment.setEndableRefreshLayout(enable);
            userTopicListFragment.setEndableRefreshLayout(enable);
        }
    }

    public boolean isRefreshLayoutEnabled() {
        if (userAlbumListFragment != null && userTopicListFragment != null &&
                userAlbumListFragment.isInited() && userTopicListFragment.isInited()) {
            return userAlbumListFragment.getRefreshLayout().isEnabled()
                    && userTopicListFragment.getRefreshLayout().isEnabled();
        } else {
            return false;
        }

    }

    @Override
    protected void handleArgs(Bundle args) {
        if (args != null) {
            user = (User) args.getSerializable(IntentParamsKey.USER);
            if (user == null) {
                user = getUser();
            }
        }
    }


}
